package com.base_java.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.base_java.common.ChanjeeException;
import com.base_java.common.ConstantPropertiesCommon;
import com.base_java.common.ServerResponse;
import com.base_java.dao.DisplayTaskManageMapper;
import com.base_java.pojo.DisplayTaskManage;
import com.base_java.service.ITaskManageService;
import com.base_java.util.LongIdGenerator;
import com.base_java.vo.Contents;
import com.base_java.vo.ContentsVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service("iTaskManageService")
public class TaskManageServiceImpl implements ITaskManageService {
    private LongIdGenerator generator = new LongIdGenerator(1L);

    @Autowired
    private DisplayTaskManageMapper displayTaskManageMapper;
    Gson gson = new Gson();

    @Override
    public ServerResponse<String> addInfo(ContentsVo contentsVo) {
        DisplayTaskManage displayTaskManage = new DisplayTaskManage();
        displayTaskManage.setUpdateTime(new Date());
        displayTaskManage.setCreateTime(new Date());
        displayTaskManage.setTaskName(contentsVo.getTaskName());
        displayTaskManage.setEnable(contentsVo.getEnable());
        Gson gson = new Gson();
        displayTaskManage.setContents(gson.toJson(contentsVo.getContentsList()));
        displayTaskManage.setId(generator.generate());
        displayTaskManage.setIntervalSeconds(contentsVo.getIntervalSeconds());
        displayTaskManage.setOrientation(contentsVo.getOrientation());
        int insert = displayTaskManageMapper.insert(displayTaskManage);
        if (insert >= 1) {
            return ServerResponse.createBySuccessMessage("添加任务成功~，可以绑定设备了");
        }
        return ServerResponse.createBySuccessMessage("添加失败~，请稍后重试");
    }

    @Override
    public ServerResponse<String> updateTask(ContentsVo contentsVo) {
        // 先查询是否存在这个任务
        DisplayTaskManage displayTaskManage = displayTaskManageMapper.selectByPrimaryKey(contentsVo.getTaskId());
        if (displayTaskManage != null) {
            //    更新表数据，选择性更新
            DisplayTaskManage displayTask = new DisplayTaskManage();
            displayTask.setTaskName(contentsVo.getTaskName());
            displayTask.setOrientation(contentsVo.getOrientation());
            displayTask.setEnable(contentsVo.getEnable());
            displayTask.setUpdateTime(new Date());
            displayTask.setIntervalSeconds(contentsVo.getIntervalSeconds());
            displayTask.setContents(gson.toJson(contentsVo.getContentsList()));

            // 根据taskId更新
            displayTask.setId(contentsVo.getTaskId());
            // 更新成功返回
            int i = displayTaskManageMapper.updateByPrimaryKeySelective(displayTask);
            if (i >= 1) {
                return ServerResponse.createBySuccessMessage("更新任务成功");
            }
            return ServerResponse.createByErrorMessage("更新失败~");
        }
        return ServerResponse.createByErrorMessage("更新任务失败");
    }

    @Override
    public ServerResponse<ContentsVo> selectTask(Long taskId) {

        ContentsVo contentsVo = new ContentsVo();
        DisplayTaskManage displayTaskManage = displayTaskManageMapper.selectByPrimaryKey(taskId);
        if (displayTaskManage != null && displayTaskManage.getTaskName() != null) {
            contentsVo.setTaskId(displayTaskManage.getId());
            contentsVo.setTaskName(displayTaskManage.getTaskName());
            contentsVo.setEnable(displayTaskManage.getEnable());
            contentsVo.setOrientation(displayTaskManage.getOrientation());
            contentsVo.setIntervalSeconds(displayTaskManage.getIntervalSeconds());
            contentsVo.setUpdateTime(displayTaskManage.getUpdateTime());
            contentsVo.setCreateTime(displayTaskManage.getCreateTime());
            Type type = new TypeToken<List<Contents>>() {
            }.getType();
            List<Contents> contentsList = gson.fromJson(displayTaskManage.getContents(), type);
            contentsVo.setContentsList(contentsList);
            return ServerResponse.createBySuccess(contentsVo);
        }
        return ServerResponse.createByErrorMessage("没有查到对应的数据~");
    }

    @Override
    public ServerResponse<String> deleteTask(Long taskId) {
        return null;
    }

    @Override
    public ServerResponse<PageInfo> taskList(int pageNum, int pageSize) {

        //startPage--start
        PageHelper.startPage(pageNum, pageSize);
        List<DisplayTaskManage> displayTaskManageList = displayTaskManageMapper.selectTaskList();
        List<ContentsVo> contentsVoList = Lists.newArrayList();
        // list 转换，然后返回分页
        for (DisplayTaskManage displayTaskManage : displayTaskManageList) {
            ContentsVo contentsVo = assembleContentsVo(displayTaskManage);
            contentsVoList.add(contentsVo);
        }
        //pageHelper-收尾
        PageInfo pageResult = new PageInfo(displayTaskManageList);
        pageResult.setList(contentsVoList);
        return ServerResponse.createBySuccess(pageResult);

    }

    private ContentsVo assembleContentsVo(DisplayTaskManage displayTaskManage) {
        ContentsVo contentsVo = new ContentsVo();

        contentsVo.setTaskId(displayTaskManage.getId());
        contentsVo.setEnable(displayTaskManage.getEnable());
        contentsVo.setIntervalSeconds(displayTaskManage.getIntervalSeconds());
        contentsVo.setOrientation(displayTaskManage.getOrientation());
        contentsVo.setTaskName(displayTaskManage.getTaskName());
        contentsVo.setCreateTime(displayTaskManage.getCreateTime());
        contentsVo.setUpdateTime(displayTaskManage.getUpdateTime());

        Type type = new TypeToken<List<Contents>>() {
        }.getType();
        List<Contents> contentsList = gson.fromJson(displayTaskManage.getContents(), type);
        contentsVo.setContentsList(contentsList);
        return contentsVo;
    }

    @Override
    public ServerResponse<String> uploadFile(MultipartFile file) {

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesCommon.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesCommon.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesCommon.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantPropertiesCommon.BUCKET_NAME;
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。

        String objectName = file.getOriginalFilename();
        // 文件名优化，存储路径优化
        objectName = UUID.randomUUID().toString() + objectName;
        String path = new DateTime().toString("yyyy/MM/dd");
        objectName = path + "/" + objectName;
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        // String filePath= "D:\\localpath\\examplefile.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 上传的文件流
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            // https://mingtai-bucket.oss-cn-beijing.aliyuncs.com/2.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + objectName;
            return ServerResponse.createBySuccess(url);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException | FileNotFoundException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            throw new ChanjeeException(2001, "上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return null;
    }


}
